<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { message } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import { doSizeInfo, doSizeAdd, doSizeEdit } from '#/api/sizeGroup'
import { useVbenForm } from '#/adapter/form'

const sizeId = ref<Number>()
const formData = ref<any>({})
const title = ref('新增尺码')
const emit = defineEmits(['fetch-data'])
const data = ref<any>()
const sizeGroupId = ref<number>(0)

/**
 * 初始化清空
 */
const initClear = async () => {
  sizeId.value = 0
  formData.value = {}
  sizeGroupId.value = 0
}

/**
 * 初始化
 */
const init = async () => {
  // 初始化逻辑
}

/**
 * 获取数据
 */
const fetchData = async () => {
  if (sizeId.value) {
    let { row } = await doSizeInfo({ id: sizeId.value })
    formApi.setValues(row)
    formData.value = row
  }
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入尺码名称',
      },
      fieldName: 'name',
      label: '尺码名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入尺码描述',
      },
      fieldName: 'description',
      label: '尺码描述',
    },
  ],
  handleSubmit: async (value) => {
    const { valid } = await formApi.validate()
    if (valid) {
      try {
        modalApi.lock()
        const submitData = {
          ...value,
          pid: sizeGroupId.value,
        }
        if (sizeId.value) {
          await doSizeEdit({ ...submitData, id: sizeId.value })
          message.success('编辑成功')
        } else {
          await doSizeAdd(submitData)
          message.success('添加成功')
        }
        emit('fetch-data')
        modalApi.close()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        modalApi.unlock()
      }
    }
  },
  handleReset: () => {
    modalApi.close()
  },
  showDefaultActions: false,
})

const [Modal, modalApi] = useVbenModal({
  class: 'w-1/3',
  destroyOnClose: true,
  onClosed: () => {
    initClear()
    formApi.resetForm()
  },
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>()
      title.value = data.value?.info?.id ? '编辑尺码' : '新增尺码'

      if (data.value?.info?.id) {
        sizeId.value = data.value.info.id
      }

      if (data.value?.sizeGroupId) {
        sizeGroupId.value = data.value.sizeGroupId
      }

      init()
      fetchData()
    }
  },
  onCancel: () => {
    modalApi.close()
  },
  onConfirm: () => {
    formApi.submitForm()
  },
})
</script>

<template>
  <Modal :title="title">
    <Form />
  </Modal>
</template>

